-- undead_contract
-- created by wangy
-- 攻击时概率触发技能（亡灵契约）

return {
    apply = function(prop, baseValue)
        return prop[3];
    end,
    -- 触发
    trigger = function(who, prop, arg)
        assert(who.type == OBJECT_TYPE_USER or who.type == OBJECT_TYPE_SUMMON, "只有玩家和召唤兽能触发");

        -- 如果是召唤兽，则取玩家
        local source = who;
        if source.type == OBJECT_TYPE_SUMMON then
            source = ME.user;
        end

        -- 不满足概率
        if DungeonM.getRandSeed("attack_skill") % 1000 >= prop[3] then
            return;
        end

        local target;
        local skillId = tonumber(prop[2]);
        local skills = SkillM.getSkillTable();
        if not skills[skillId] then
            return;
        end

        -- 目标
        local grid;
        if not SkillM.needTarget(skillId) then
            target = source;
        elseif not arg:isDead() then
            target = arg;
            -- 对BOSS不触发
            if target:isBoss() then
                return;
            end
        else
            -- 亡灵契约特殊处理，只会针对当前怪物
            if skillId == 78 then
                return;
            end

            for p = 1, DUNGEON_WIDTH * DUNGEON_HEIGHT do
                grid = DungeonM.getGridByPos(p);

                -- 是未死亡的怪物
                if grid:isOpened() and
                   grid:isMonster() and
                   not grid.monster:isDead() then
                    target = grid.monster;
                    break;
                end
            end

            -- 已经没有目标了，不处理
            if not target then
                return;
            end
        end

        local round = CombatM.getRound();

        -- 触发特技发动事件
        EventMgr.fire(event.SPECIAL_SKILL_TRIGGER, { propId = prop[1] });

        SkillM.apply(source, target, skillId, round);
    end,

    record = function(target, prop, path)
        return false;
    end
};
